package cn.openread.demo.netty.ws;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 处理Object
 */
@Slf4j
public class ObjectWebSocketFrameHandler extends SimpleChannelInboundHandler<Object> {

    /**
     * 这里集中存放channel
     */
    private static final ScheduledExecutorService scheduledExecutorService =
            Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
                                Object object) {
        Channel incoming = ctx.channel();

        log.debug("接受到的数据：" + object);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        log.debug("[设备端] - " + incoming.remoteAddress() + " 加入");
        incoming.writeAndFlush("[设备端] - " + incoming.remoteAddress() + " 加入");


        scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                log.debug("进行job运行============>");

//                incoming.writeAndFlush(new PingWebSocketFrame());
//                incoming.writeAndFlush(new PongWebSocketFrame());
                incoming.writeAndFlush(new TextWebSocketFrame("普通消息"));
            }
        }, 1L, 2L, TimeUnit.SECONDS);
//        channels.add(incoming);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();

//        channels.writeAndFlush(new TextWebSocketFrame("[SERVER] - " + incoming.remoteAddress() + " 离开"));

        log.warn("Client:" + incoming.remoteAddress() + "离开");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        log.debug("Client:" + incoming.remoteAddress() + "在线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        Channel incoming = ctx.channel();
        log.error("Client:" + incoming.remoteAddress() + "掉线");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error(cause.toString());
        ctx.close();
    }

}
